/*
 * @Description: 前端导出数据 xlsx 工具函数
 * @Author: 0001100986/LiuShuai
 * @Date: 2021-06-22 14:09:49
 * @LastEditTime: 2021-09-24 10:44:54
 * @LastEditors: 0001100986/LiuShuai
 */
import XLSX from 'xlsx';
import dayjs from 'dayjs';
const FileSaver = require('file-saver');
export function downloadMater (data) {
  const defaultCellStyle = {
    font: {
      name: 'Verdana',
      sz: 11,
      color: 'FF00FF88'
    },
    fill: {
      fgColor: {
        rgb: 'FFFFAA00'
      }
    }
  };
  const wopts = {
    bookType: 'xlsx',
    bookSST: false,
    type: 'binary',
    defaultCellStyle: defaultCellStyle,
    showGridLines: false
  };
  const wb = {
    SheetNames: ['Sheet1'],
    Sheets: {},
    Props: {}
  };
  wb.Sheets['Sheet1'] = XLSX.utils.json_to_sheet(data);
  // 创建二进制对象写入转换好的字节流
  let tmpDown = new Blob([s2ab(XLSX.write(wb, wopts))], { type: 'application/octet-stream' });
  FileSaver.saveAs(tmpDown, dayjs().format('YYYY-MM-DD HH:mm:ss') + '.xlsx');
}

// 字符串转字符流
function s2ab (s) {
  if (typeof ArrayBuffer !== 'undefined') {
    // eslint-disable-next-line no-inner-declarations
    let buf = new ArrayBuffer(s.length);
    let view = new Uint8Array(buf);
    for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
    return buf;
  } else {
    // eslint-disable-next-line no-inner-declarations
    let buf = new Array(s.length);
    for (let i = 0; i !== s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF;
    return buf;
  }
}